package com.enjoy.concurrent.ch10.completionservice;

import org.junit.Test;

import java.util.concurrent.*;

public class CompletionServiceTest {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        CompletionService<String> completionService = new ExecutorCompletionService<>(executorService);

        completionService.submit(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "休眠3s";
        });

        completionService.submit(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "休眠2s";
        });

        completionService.submit(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "休眠1s";
        });

        Future<String> future;

        while (true) {
            if ((future = completionService.take()) != null) {
                System.out.println("future.get() = " + future.get());
            } else {
                break;
            }
        }

        executorService.shutdown();

    }


    @Test
    public void test1() throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        System.out.println("--------------------");
        Future<String> future1 = executorService.submit(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "休眠3s");
        Future<String> future2 = executorService.submit(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "休眠2s");
        Future<String> future3 = executorService.submit(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "休眠1s");

        System.out.println("future1.get() = " + future1.get());
        System.out.println("future2.get() = " + future2.get());
        System.out.println("future3.get() = " + future3.get());
    }
}
